package com.tristia.resources.impl;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import twitter4j.http.RequestToken;

import com.tristia.dao.GenericDao;
import com.tristia.entity.Book;
import com.tristia.entity.OAuthObject;
import com.tristia.entity.util.RandomGenerator;

@Component
@Path("/twitter")
@Scope("singleton")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML })
public class TwitterResWs {
	@Resource
	GenericDao<Book, Long> bookDao;
	@Resource
	GenericDao<OAuthObject, Long> oauthObjectDao;
	@Context 
	UriInfo ui;
	private Logger log = Logger.getLogger(this.getClass());
	
    OAuthConsumer consumer = new DefaultOAuthConsumer(
            "hXGis9WsKpbTM4vM7csnYg",
            "FVB6NljXWDyOUjuMRFUWRwwr4pR55Oa1op9plTVSTg");

    OAuthProvider provider = new DefaultOAuthProvider("http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");
    
    String authUrl;
    
    Twitter twitter = new TwitterFactory().getInstance();
    RequestToken requestToken;
    
	public TwitterResWs() {
		twitter.setOAuthConsumer("hXGis9WsKpbTM4vM7csnYg", "FVB6NljXWDyOUjuMRFUWRwwr4pR55Oa1op9plTVSTg");
        try {
        	InetAddress addr = InetAddress.getLocalHost();
			String addrStr = addr.getHostAddress();
			requestToken = twitter.getOAuthRequestToken("http://"+addrStr+":9999/tristia/restws/twitter/callback");
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@GET
	@Path("/oauth")
	public Response getAuth() throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, TwitterException {
		log.info("getAuth entered");
		Response r;
		
//		authUrl = provider.retrieveRequestToken(consumer, "http://evilkiller.oicp.net:9999/tristia/restws/books/twitter/callback");
//		String authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND);

//        System.out.println("Request token: " + consumer.getToken());
//        System.out.println("Token secret: " + consumer.getTokenSecret());

/*        System.out.println("Now visit:\n" + authUrl
                + "\n... and grant this app authorization");*/
        
//        twitter.setOAuthConsumer("hXGis9WsKpbTM4vM7csnYg", "FVB6NljXWDyOUjuMRFUWRwwr4pR55Oa1op9plTVSTg");
//        requestToken = twitter.getOAuthRequestToken("http://evilkiller.oicp.net:9999/tristia/restws/twitter/callback");

        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());

        OAuthObject oauthObject = new OAuthObject(1, requestToken.getAuthorizationURL());
        
		r = Response.ok(oauthObject).build();
		return r;
	}
	
	@GET
	@Path("/callback")
//	@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_XML })
	public Response sentTweet(@QueryParam("oauth_verifier") String oauth_verifier) throws OAuthMessageSignerException, OAuthNotAuthorizedException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, TwitterException {
		log.info("sentTweet entered");
		Response r;
        System.out.println("Fetching access token from Twitter...");

//        provider.retrieveAccessToken(consumer, oauth_verifier);

//        System.out.println("Access token: " + consumer.getToken());
//        System.out.println("Token secret: " + consumer.getTokenSecret());
        
        AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, oauth_verifier);
        
        OAuthObject oauthObject = new OAuthObject(1, requestToken.getAuthorizationURL());
        oauthObject.setConsumerKey("hXGis9WsKpbTM4vM7csnYg");
        oauthObject.setConsumerSecret("FVB6NljXWDyOUjuMRFUWRwwr4pR55Oa1op9plTVSTg");
        oauthObject.setToken(accessToken.getToken());
        oauthObject.setTokenSecret(accessToken.getTokenSecret());
        oauthObjectDao.save(oauthObject);
        
        Status status = twitter.updateStatus("twitter4j test from tristia system" + RandomGenerator.getRandomInt());
        
        System.out.println("Successfully updated the status to [" + status.getText() + "].");

//        URL url = new URL("http://twitter.com/statuses/mentions.xml");
//        URL url = new URL("http://api.twitter.com/1/statuses/update.xml");
//        HttpURLConnection request = (HttpURLConnection) url.openConnection();
//        request.setRequestMethod("POST");
//        request.addRequestProperty("status", "initial test from tristia system");

//        consumer.sign(request);

//        System.out.println("Sending request to Twitter...");
//        request.connect();

//        System.out.println("Response: " + request.getResponseCode() + " "
//                + request.getResponseMessage());
        
/*        Twitter twitter = new TwitterFactory().getInstance("killercentury","4344911");
        Status status = twitter.updateStatus("twitter4j test from tristia system");
        System.out.println("Successfully updated the status to [" + status.getText() + "].");*/

        
/*        Client client = Client.create();
        WebResource webResource = client.resource("http://api.twitter.com/1/statuses/update.xml");
        MultivaluedMap formData = new MultivaluedMapImpl();
        formData.add("status", "initial test from tristia system");
        ClientResponse response = webResource.type("application/x-www-form-urlencoded").post(ClientResponse.class, formData);

        log.info("ClientResponse Code: "+response.getClientResponseStatus().getStatusCode());*/
		r = Response.ok().build();
		return r;
	}

}
